/**
 * 整合所有子路由
 */
const router = require('koa-router')();
const inflection = require('inflection')
const admin = require('./admin');
const uploads = require('./admin/uploads');
const login = require('./admin/login');
const jwt = require("jsonwebtoken");
const AdminUser = require('../models/AdminUser');

router.use(login.routes())

router.use(async (ctx, next) => {
    const token = String(ctx.request.header.authorization || "").split(' ').pop()
    ctx.assert(token, 401, "请提供 jwt token")

    let id, errorMsg
    try {
        const decoded = jwt.verify(token, "secret")
        id = decoded.id || undefined
    } catch (error) {
        errorMsg = error.message
    }
    ctx.assert(id, 401, errorMsg)

    ctx.request.user = await AdminUser.findById(id)
    ctx.assert(ctx.request.user, 401, "请先登录")
    await next()
})

router.use('/api/admin/rest/:resourse', async (ctx, next) => {
    const modelName = inflection.classify(ctx.params.resourse)
    ctx.Model = require(`../models/${modelName}`)
    await next()
}, admin.routes())

router.use(uploads.routes())


module.exports = router;